package com.lolc.utils;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue {

	private static Map<Object, Integer> sortByComparator(Map<Object, Integer> unsortMap, final boolean order) {

		List<Entry<Object, Integer>> list = new LinkedList<Entry<Object, Integer>>(unsortMap.entrySet());

		// Sorting the list based on values
		Collections.sort(list, new Comparator<Entry<Object, Integer>>() {
			public int compare(Entry<Object, Integer> o1, Entry<Object, Integer> o2) {
				if (order) {
					return o1.getValue().compareTo(o2.getValue());
				} else {
					return o2.getValue().compareTo(o1.getValue());
				}
			}
		});

		// Maintaining insertion order with the help of LinkedList
		Map<Object, Integer> sortedMap = new LinkedHashMap<Object, Integer>();
		for (Entry<Object, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}

		return sortedMap;
	}
}